//
//  B_RightTopAlertView.m
//  Application
//
//  Created by 薛小刚 on 2018/8/11.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_RightTopAlertView.h"
#import "B_ImageLabelTVC.h"

@implementation B_RightTopAlertView

+ (instancetype) initB_RightTopAlertView {
    return [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil].lastObject;
}

- (void) show {
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(KeyWindow.mas_top);
        make.left.equalTo(KeyWindow.mas_left);
        make.right.equalTo(KeyWindow.mas_right);
        make.bottom.equalTo(KeyWindow.mas_bottom);
    }];
}

- (void)setDataArray:(NSArray *)dataArray {
    _dataArray = dataArray;
    [self.B_TableView registerNib:[UINib nibWithNibName:@"B_ImageLabelTVC" bundle:nil] forCellReuseIdentifier:@"B_ImageLabelTVC"];
    CGFloat height = _dataArray.count * 55 > 220 ? 220 : _dataArray.count * 55;
    [self.B_TableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(height));
    }];
    [self.B_TableView reloadData];
}

#pragma mark -> tableView datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    B_ImageLabelTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_ImageLabelTVC" forIndexPath:indexPath];
    if ([self.dataArray[indexPath.row] isKindOfClass:[NSDictionary class]]) {
        cell.titleLabel.text = self.dataArray[indexPath.row][@"title"];
        cell.imageView.image = [UIImage imageNamed:self.dataArray[indexPath.row][@"image"]];
    } else {
        cell.titleLabel.text = self.dataArray[indexPath.row];
    }
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 54;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self removeFromSuperview];
    if (self.selectIndex) {
        self.selectIndex(indexPath);
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self removeFromSuperview];
}
@end
